package com.cius.ssm.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by ciuscheung on 17/4/13.
 */
public class LoginInterceptor implements HandlerInterceptor {

    //进人Handler之前执行
    //用于身份认证,身份授权
    //如果身份认证不通过,表示当前用户没有登录,需要此方法拦截不再向下执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //获取请求url
        String url = httpServletRequest.getRequestURI();

        //判断url是否为公开地址(实际开发中将公开地址放入地址配置文件中)
        //这路公开地址是登录提交的地址

        if(url.indexOf("login.action")>=0){
            //如果登录提交,放行
            return true;
        }

        //判断session
        HttpSession session = httpServletRequest.getSession();
        //从session中取出用户身份信息
        String username = (String) session.getAttribute("username");
        if(username!=null){
            //身份存在,放行
            return true;
        }
        //执行到这里表示用户需要认证,需要跳转到登录页面
        httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(httpServletRequest,httpServletResponse);

        //return true表示放行
        //return false 表示拦截,不向下执行
        return false;
    }

    //进入handler之后,返回modelAndView之前执行
    //应用场景:从modelAndView出发,将公用模型数据(比如菜单导航)在这里传到视图,也可以在这指定同意视图
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    //执行handler完成执行此方法
    //应用场景:同意日志管理,同意日志处理
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
